/*
Copyright 2012 Frederic Langlet
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
you may obtain a copy of the License at

                http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package bloomfilter;

public class Test
{
   public static void main(String[] args)
   {
      int errorRate = 1024/4;

      for (int ii=0; ii<5; ii++)
      {
         BloomFilter<String> filter = new BloomFilter<String>(errorRate, 1000);
         errorRate >>= 1;
         int maxAdd = 999;
         int maxTest = 50000;

         for (int i=0; i<maxAdd; i++)
         {
            if (filter.add(String.valueOf(i)) == false)
            {
               System.out.println("Could not add "+i);
               break;
            }
         }

         System.out.println(filter);
         int fp = 0;

         for (int i=0; i<maxTest; i++)
         {
            if (filter.contains(String.valueOf(i)) == true)
            {
               if (i >= maxAdd)
               {
//                  System.out.println("False positive for value "+i);
                  fp++;
               }
            }
            else
            {
               if (i < maxAdd)
               {
                  System.out.println("Error for value "+i);
                  System.exit(1);
               }
            }
         }

         maxTest -= maxAdd;
         System.out.println("Actual error rate: "+ (((fp * 100) + (maxTest/2)) / maxTest)+"%\n\n\n");
      }

      System.out.println("Speed test (filter capacity = 1000, error rate = 1%)");
      final int iter1 = 1000;
      final int iter2 = 1000;
      final int iter3 = 10000;
      long delta1 = 0;
      long delta2 = 0;

      for (int ii=0; ii<iter1; ii++)
      {
         BloomFilter<String> filter = new BloomFilter<String>(11, 1000);
         long before, after;
         before = System.nanoTime();

         for (int i=0; i<iter2; i++)
            filter.add(String.valueOf(i));

         after = System.nanoTime();
         delta1 += (after - before);
         before = System.nanoTime();

         for (int i=0; i<iter3; i++)
            filter.contains(String.valueOf(i));

         after = System.nanoTime();
         delta2 += (after - before);
      }

      System.out.println(iter1*iter2+" filter.add() iterations");
      System.out.println("Elapsed [ms]: "+delta1/1000000L);
      System.out.println(iter2*iter3+" filter.contains() iterations");
      System.out.println("Elapsed [ms]: "+delta2/1000000L);
   }
}